//
//  JYSearchHistoryManager.m
//  JYFarm
//
//  Created by 花花 on 2017/10/20.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYSearchHistoryManager.h"

@interface JYSearchHistoryManager()

@property(nonatomic)NSMutableArray *searchHistoryMArray;
@end

@implementation JYSearchHistoryManager



+(JYSearchHistoryManager *)shareInstance{

    static JYSearchHistoryManager *searchHistory = nil;
 
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!searchHistory) {
        
            searchHistory = [[JYSearchHistoryManager alloc]init];
        }
        
    });

    return searchHistory;
}

- (instancetype)init{

    if (self = [super init]) {
        
        NSArray *fileArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePath]];
        for (JYSearchModel *model in fileArray) {
            if (nil != model) {
                [self.searchHistoryMArray addObject:model];
            }
        }
        
    }
    return self;
    
}

- (NSString *)getFilePath{

    return   [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"SearchHistory.plist"];
    


}
//获取历史搜索记录
- (NSMutableArray *)getSearchHistoryArray{

    return [JYSearchHistoryManager shareInstance].searchHistoryMArray;

}

//清空搜索记录
- (void)clearAllSearchHistory{

    [[JYSearchHistoryManager shareInstance].searchHistoryMArray removeAllObjects];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kClearSearchHistoryNotification object:nil];
    
    [[NSFileManager defaultManager]removeItemAtPath:[self getFilePath] error:nil];
}

//保存搜索历史到文件
- (void)saveSearchItemToHistory:(JYSearchModel *)model{
    //已经保存过的 不再保存
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF.name = %@",model.name];
    
    NSArray *games = [self.searchHistoryMArray filteredArrayUsingPredicate:pre];
    if (games.count>0) return;
    
//    [self.searchHistoryMArray insertObject:model atIndex:0];
    // 保存记录10个历史记录
    if (self.searchHistoryMArray.count>10) [self.searchHistoryMArray removeLastObject];
    
    [NSKeyedArchiver archiveRootObject:self.searchHistoryMArray toFile:[self getFilePath]];
    
    //发送保存搜索历史成功的通知 刷新页面数据
    [[NSNotificationCenter defaultCenter]postNotificationName:kSaveHistoryItemSuccessNotification object:nil];
    
}

-(NSMutableArray *)searchHistoryMArray{
    
    if (!_searchHistoryMArray) {
        _searchHistoryMArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _searchHistoryMArray;
}


@end
